"""
代码尝试专用脚本（空壳模板）
- 用于调试、测试新功能或片段
"""

import os
import time

import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import pandas as pd
import scipy.stats
import seaborn as sns
from matplotlib.font_manager import FontProperties
from sklearn.covariance import GraphicalLasso, LedoitWolf
from sklearn.preprocessing import StandardScaler
from src.mgm import (
    add_age_group,
    bootstrap_diff,
    build_network_from_adj,
    compare_edge_structure,
    compare_network_structure,
    draw_multi_year_agegroup_networks,
    draw_multi_year_networks,
    draw_network,
    draw_network_subplot,
    filter_vars,
    get_chinese_name,
    get_network_annotation,
    get_node_metrics,
    plot_density_heatmap,
    plot_happiness_centrality_bar,
    preprocess_data,
    run_ledoitwolf,
    run_mgm,
    save_and_show_fig,
    test_edge_weight_diff,
    test_node_centrality_diff,
)

from tqdm import tqdm

if __name__ == "__main__":
    print("=" * 40)
    start_time_str = time.strftime("%Y-%m-%d %H:%M:%S")
    start_time = time.time()
    print(f"⏱ 代码尝试开始 {start_time_str}")
    print("=" * 40)

    # 假定 results 已由 draw_multi_year_agegroup_networks 得到
    # 这里仅演示统计所有组的整体指标
    # 请确保 results 已定义并包含 (year, age_group), G 键值对
    summary = []
    for (year, age_group), G in results.items():
        n_components = nx.number_connected_components(G)
        largest_cc = max(nx.connected_components(G), key=len)
        largest_cc_size = len(largest_cc)
        isolated = list(nx.isolates(G))
        centrality = nx.betweenness_centrality(G)
        core_nodes = sorted(centrality.items(), key=lambda x: x[1], reverse=True)[:3]
        density = nx.density(G)
        if G.number_of_edges() > 0 and largest_cc_size > 1:
            avg_path_length = nx.average_shortest_path_length(G.subgraph(largest_cc))
        else:
            avg_path_length = float('nan')
        clustering = nx.average_clustering(G)
        summary.append({
            "年份": int(year),
            "年龄组": str(age_group),
            "节点总数": G.number_of_nodes(),
            "边总数": G.number_of_edges(),
            "连通分量数": n_components,
            "最大分量节点数": largest_cc_size,
            "网络密度": round(density, 3),
            "平均路径长度": round(avg_path_length, 3) if not pd.isna(avg_path_length) else "NA",
            "平均聚类系数": round(clustering, 3),
            "孤立节点": ",".join(isolated),
            "核心节点": ",".join([n for n, _ in core_nodes])
        })
    df_summary = pd.DataFrame(summary)
    print("\n各年份-年龄组网络结构对比（含整体指标）：")
    print(df_summary.to_string(index=False))

    end_time_str = time.strftime("%Y-%m-%d %H:%M:%S")
    end_time = time.time()
    print("=" * 40)
    print(f"⌛️ 代码尝试结束 {end_time_str}")
    duration = end_time - start_time
    print(f"总耗时：{int(duration)} 秒（{duration/60:.2f} 分钟）")
    print("=" * 40)

